//
//  MyActityVC.m
//  SelfDrivingTravelling-IOS
//
//  Created by Teplot_01 on 16/8/31.
//  Copyright © 2016年 Teplot_01. All rights reserved.
//

#import "MyActityVC.h"
#import "MyActityCell.h" 
#import "ActivityDetailVC.h"
#import "LeaderActityManVC.h"
#import "CreateActivityVC.h"
#import "MyActitySignListVC.h"

@interface MyActityVC ()<UITableViewDelegate,UITableViewDataSource>

@end

@implementation MyActityVC
{
    UITableView *_tableView;
    NSInteger _currentPage;
    
    NSString *statusStr;
    //请求下来的字典
    NSDictionary *_responseDic;
    //请求下来的数组
    NSMutableArray *_responseArr;
    
    UIButton *_normalBtn;
    UIButton *_willBegBtn;
    UIButton *_ingBtn;
    UIButton *_endBtn;
}
- (void)viewWillAppear:(BOOL)animated{
    _currentPage = 1;
    [self requsetForMyJionActityListWithCurrentPage:_currentPage isFirst:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = White_Color;
    self.title = @"我的活动";
    _responseArr = [NSMutableArray array];
    //默认参数
    statusStr = @"";
    [self initView];
    [self initTableView];
    _tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
}
#pragma - mark RequetForActityList
- (void)requsetForMyJionActityListWithCurrentPage:(NSInteger)currentPage isFirst:(BOOL)isFirst{
    
    NSDictionary *parameters = @{
                                  @"userId": [NSString readToNSDefaultsWithKey:kId],
                                  @"status": statusStr,
                                  @"pageNum": @(_currentPage),
                                  @"pageSize": @"10",
                                  };
    [SVProgressHUD showWithStatus:@"请求中"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:@"http://115.28.152.130/tour/v1/activity/listWithUserID.action" parameters:parameters success:^(NSURLSessionDataTask *operation, id responseObject) {
        [_tableView.mj_header endRefreshing];
        _responseDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@>>>>",_responseDic);
        NSArray *temp = _responseDic[@"list"];
        NSString *error = _responseDic[@"code"];
        if (![_responseDic[@"code"] isEqualToString:@"0000"]&&![_responseDic[@"code"] isEqualToString:@"3003"]) {
            [SVProgressHUD showErrorWithStatus:[NSString errorStringWithCode:error]];
        }
        if ([_responseDic[@"code"] isEqualToString:@"4006"]) {
            [SVProgressHUD showImage:nil status:@"请重新登陆"];
            [_tableView reloadData];
        }
        if ([_responseDic[@"code"] isEqualToString:@"3003"]) {
            [SVProgressHUD showImage:nil status:@"没有当前类型的活动"];
            [_responseArr removeAllObjects];
            [_tableView reloadData];
        }else{
            if (isFirst) {
                if (temp.count == 0) {
                    [SVProgressHUD showImage:nil status:@"暂无数据"];
                }
                [_responseArr removeAllObjects];
            }
            [_responseArr addObjectsFromArray:temp];
            
            if (temp.count < 10) {
                [_tableView.mj_footer endRefreshingWithNoMoreData];
            }
            else {
                [_tableView.mj_footer endRefreshing];
            }
            //请求成功
            [_tableView reloadData];
            [SVProgressHUD dismiss];
        }
        
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"请求活动列表失败"];
        [SVProgressHUD dismiss];
    }];
}
- (void)initView{
    UIView* customView = [[UIView alloc] initWithFrame:CGRectMake(0, 66, KScreenWidth, 35)];
    customView.backgroundColor = White_Color;
    int margn = (KScreenWidth-16-85-60-50-50)/3;
    _normalBtn = [[UIButton alloc]initWithFrame:CGRectMake(8, 0, 85, 35)];
    [_normalBtn setTitle:@"时间由近及远" forState:UIControlStateNormal];
    [_normalBtn.titleLabel setFont:[UIFont systemFontOfSize:13]];
    [_normalBtn setTitleColor:Orange_Color forState:UIControlStateNormal];
    [_normalBtn addTarget:self action:@selector(normalBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [customView addSubview:_normalBtn];
    _willBegBtn = [[UIButton alloc]initWithFrame:CGRectMake(85+8+margn, 0, 60, 35)];
    [_willBegBtn setTitle:@"即将开始" forState:UIControlStateNormal];
    [_willBegBtn.titleLabel setFont:[UIFont systemFontOfSize:13]];
    [_willBegBtn setTitleColor:Black_Color forState:UIControlStateNormal];
    [_willBegBtn addTarget:self action:@selector(willBegBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [customView addSubview:_willBegBtn];
    _ingBtn = [[UIButton alloc]initWithFrame:CGRectMake(85+8+60+margn*2, 0, 50, 35)];
    [_ingBtn setTitle:@"进行中" forState:UIControlStateNormal];
    [_ingBtn.titleLabel setFont:[UIFont systemFontOfSize:13]];
    [_ingBtn setTitleColor:Black_Color forState:UIControlStateNormal];
    [_ingBtn addTarget:self action:@selector(ingBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [customView addSubview:_ingBtn];
    _endBtn = [[UIButton alloc]initWithFrame:CGRectMake(85+60+60+margn*3, 0, 50, 35)];
    [_endBtn setTitle:@"已结束" forState:UIControlStateNormal];
    [_endBtn.titleLabel setFont:[UIFont systemFontOfSize:13]];
    [_endBtn setTitleColor:Black_Color forState:UIControlStateNormal];
    [_endBtn addTarget:self action:@selector(endBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [customView addSubview:_endBtn];
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 34, KScreenWidth, 1)];
    lineView.backgroundColor = superBackgroundColor;
    [customView addSubview:lineView];
    [self.view addSubview:customView];
}
- (void)initTableView{
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 101, KScreenWidth, KScreenHeight-66-35)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
    [self refreshDown];
    [self refreshLoadMore];
}
//下拉刷新
- (void)refreshDown{
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        _currentPage = 1;
        [self requsetForMyJionActityListWithCurrentPage:_currentPage isFirst:YES];
    }];
}
//上提加载更多
- (void)refreshLoadMore{
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        _currentPage++;
        [self requsetForMyJionActityListWithCurrentPage:_currentPage isFirst:NO];
    }];
}
#pragma -mark UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _responseArr.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 85;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MyActityCell *cell = [[NSBundle mainBundle]loadNibNamed:@"MyActityCell" owner:nil options:nil][0];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.titleLb.text = _responseArr[indexPath.row][@"title"];
    cell.cityLb.text = _responseArr[indexPath.row][@"destination"];
    NSString *timeStr = _responseArr[indexPath.row][@"stratTime"];
    timeStr = [timeStr substringToIndex:10];
    cell.timeLb.text = timeStr;
    NSString *endStr = _responseArr[indexPath.row][@"endTime"];
    endStr = [endStr substringToIndex:10];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *starDate=[formatter dateFromString:timeStr];
    NSDate *endDate=[formatter dateFromString:endStr];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    unsigned int unitFlags = NSCalendarUnitDay;
    NSDateComponents *times = [calendar components:unitFlags fromDate:starDate toDate:endDate options:0];
    cell.spendTimeLb.text = [NSString stringWithFormat:@"%ld%@",(long)[times day],@"天"];
    NSString *iconUrl = _responseArr[indexPath.row][@"coverImgURL"];
    [cell.icon sd_setImageWithURL:[NSURL URLWithString:iconUrl] placeholderImage:[UIImage imageNamed:@"france"]];
    cell.icon.layer.masksToBounds = YES;
    cell.icon.contentMode = UIViewContentModeScaleAspectFill;
    if ([_responseArr[indexPath.row][@"status"]isEqualToString:@"1"]) {
        cell.image.image = [UIImage imageNamed:@"报名中"];
    }
    if ([_responseArr[indexPath.row][@"status"]isEqualToString:@"2"]) {
        cell.image.image = [UIImage imageNamed:@"进行中"];
    }
    if ([_responseArr[indexPath.row][@"status"]isEqualToString:@"3"]) {
        cell.image.image = [UIImage imageNamed:@"印章-拷贝"];
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    MyActitySignListVC *vc = [[MyActitySignListVC alloc]init];
    vc.hidesBottomBarWhenPushed = YES;
    vc.actityId = _responseArr[indexPath.row][@"id"];
    vc.htmlUrl = _responseArr[indexPath.row][@"htmlUrl"];
    vc.status = _responseArr[indexPath.row][@"status"];
    [self.navigationController pushViewController:vc animated:YES];
}
//Btn点击事件
- (void)normalBtnAction{
    statusStr = @"";
    _currentPage = 1;
    [self requsetForMyJionActityListWithCurrentPage:_currentPage isFirst:YES];
    [_normalBtn setTitleColor:Orange_Color forState:UIControlStateNormal];
    [_willBegBtn setTitleColor:Black_Color forState:UIControlStateNormal];
    [_ingBtn setTitleColor:Black_Color forState:UIControlStateNormal];
    [_endBtn setTitleColor:Black_Color forState:UIControlStateNormal];
}
- (void)willBegBtnAction{
    statusStr = @"1";
    _currentPage = 1;
    [self requsetForMyJionActityListWithCurrentPage:_currentPage isFirst:YES];
    [_normalBtn setTitleColor:Black_Color forState:UIControlStateNormal];
    [_willBegBtn setTitleColor:Orange_Color forState:UIControlStateNormal];
    [_ingBtn setTitleColor:Black_Color forState:UIControlStateNormal];
    [_endBtn setTitleColor:Black_Color forState:UIControlStateNormal];
}
- (void)ingBtnAction{
    statusStr = @"2";
    _currentPage = 1;
    [self requsetForMyJionActityListWithCurrentPage:_currentPage isFirst:YES];
    [_normalBtn setTitleColor:Black_Color forState:UIControlStateNormal];
    [_willBegBtn setTitleColor:Black_Color forState:UIControlStateNormal];
    [_ingBtn setTitleColor:Orange_Color forState:UIControlStateNormal];
    [_endBtn setTitleColor:Black_Color forState:UIControlStateNormal];
}
- (void)endBtnAction{
    statusStr = @"3";
    _currentPage = 1;
    [self requsetForMyJionActityListWithCurrentPage:_currentPage isFirst:YES];
    [_normalBtn setTitleColor:Black_Color forState:UIControlStateNormal];
    [_willBegBtn setTitleColor:Black_Color forState:UIControlStateNormal];
    [_ingBtn setTitleColor:Black_Color forState:UIControlStateNormal];
    [_endBtn setTitleColor:Orange_Color forState:UIControlStateNormal];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
